package com.hznu.ez4life.modules.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hznu.ez4life.modules.entity.Helpapply;
import com.hznu.ez4life.modules.dao.HelpapplyDao;
import com.hznu.ez4life.modules.entity.Orders;
import com.hznu.ez4life.modules.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DragonDoor
 * @since 2019-07-25
 */
@Service
public class HelpapplyServiceImpl extends ServiceImpl<HelpapplyDao, Helpapply> implements HelpapplyService {

    @Autowired
    ItemService itemService;
    @Autowired
    BuildingService buildingService;
    @Autowired
    UserService userService;
    @Autowired
    OrdersService ordersService;

    public void addOne(Helpapply helpapply)
    {
        helpapply.setApplytime(new Date(System.currentTimeMillis()));
        this.insert(helpapply);
    }

    @Override
    public Helpapply findOne(Integer id)
    {
        Helpapply helpapply = this.selectById(id);
        setDetail(helpapply);
        if(helpapply.getNuserId()!=null)
        {
            helpapply.setNuser(userService.findById(helpapply.getNuserId()));
        }
        return helpapply;
    }
    @Override
    public void agreeApply(Integer id)
    {
        Helpapply helpapply = this.selectById(id);
        helpapply.setStatu(2);
        Orders orders = new Orders();
        orders.setNuserId(helpapply.getNuserId());
        orders.setHuserId(helpapply.getHuserId());
        orders.setItemId(helpapply.getItemId());
        orders.setTobuildingId(helpapply.getTobuildingId());
        orders.setBegintime(helpapply.getBegintime());
        orders.setEndtime(helpapply.getEndtime());
        orders.setPrice(helpapply.getPrice());
        orders.setDes(helpapply.getDes());
        ordersService.addOne(orders);
        this.updateById(helpapply);
    }

    @Override
    public List<Helpapply> findBatchByHuserId(Integer huserId)
    {
        List<Helpapply> helpapplies = this.selectList(new EntityWrapper<Helpapply>().eq("huser_id",huserId));
        for(Helpapply helpapply : helpapplies)
        {
            setDetail(helpapply);

        }
        return helpapplies;
    }

    private void setDetail(Helpapply helpapply)
    {
        if(helpapply.getItemId()!=null)
        {
            helpapply.setItem(itemService.findById(helpapply.getItemId()));
        }
        if(helpapply.getTobuildingId()!=null)
        {
            helpapply.setTobuilding(buildingService.selectById(helpapply.getTobuildingId()));
        }
    }
}
